<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class RegistrationForm extends CFormModel
{
	public $agree;
	public $email;
	public $first_name;
	public $last_name;
	public $fio;
	public $password;
	public $password_twice;
	public $sex;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('email, first_name, last_name, password, password_twice, sex', 'required'),
			// agree needs to be a boolean
			array('agree', 'boolean'),
			array('password', 'length', 'max'=>100,'min'=>6),
			array('password_twice', 'compare', 'compareAttribute'=>'password','message'=>'Пароли не совпадают'),
			array('email','unique', 'className' => 'Users'),
			array('password_twice', 'safe'),
			array('email', 'email','checkMX'=>true),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'iread'=>'Да, я прочитал и согласен с условиями пользовательского соглашения',
			'email'=>'E-mail',
			'first_name'=>'Имя',
			'last_name'=>'Фамилия',
			'fio'=>'ФИО',
			'password'=>'Пароль',
			'password_twice'=>'Повторить пароль',
			'agree'=>'Я согласен с правилами использования',
			'sex'=>'Ваш пол',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		$this->_identity=new UserIdentity($this->email, $this->password);
		if(!$this->_identity->authenticate())
			$this->addError('password','Не правильный пароль или e-mail.');
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->email,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}
}
